package com.zh.flowable.support;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * 用于方便获取SpringContext对象
 *
 * @author ZH
 * @date 16:43 2021/5/15
 */
@Component
public final class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public synchronized void setApplicationContext(ApplicationContext context) throws BeansException {
        if (SpringContextHolder.context == null)
            SpringContextHolder.context = context;
    }

    public static <T> T getBean(Class<T> requiredType) {
        return context.getBean(requiredType);
    }

    public static <T> T getBean(String beanName, Class<T> requiredType) {
        return context.getBean(beanName, requiredType);
    }

    public static <T> List<T> getBeansOfType(Class<T> requiredType) {
        return new ArrayList<>(context.getBeansOfType(requiredType).values());
    }

    public static String getProperty(String key) {
        return context.getEnvironment().getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        return context.getEnvironment().getProperty(key, defaultValue);
    }

    public static String getPropertyOrThrow(String key) {
        String property = context.getEnvironment().getProperty(key);
        if (property == null || property.isEmpty())
            throw new NoSuchElementException(key + "缺失,找不到");
        return property;
    }

}
